package com.kgc.mall.servlet;

import cn.hutool.core.util.StrUtil;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class BaseServlet extends HttpServlet {

    @Override
    public void service(ServletRequest req, ServletResponse resp) throws ServletException, IOException {
        HttpServletRequest  request  = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
        String name = request.getParameter("action");
        if(StrUtil.isNotEmpty(name)){
            Class clazz = this.getClass();
            Method method = null;
            try {
                method = clazz.getDeclaredMethod(name, HttpServletRequest.class, HttpServletResponse.class);
                method.setAccessible(true);
                method.invoke(this,request,response);
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
                response.sendError(500,"没有查找到[" + name + "]方法，请您检查");
            } catch (IllegalAccessException e) {
                e.printStackTrace();
                response.sendError(500,"您没有访问[" + name + "]方法的权限");
            } catch (InvocationTargetException e) {
                e.printStackTrace();
                response.sendError(500,"您调用的["+ name + "]方法的内部抛出错误,错误消息：" + e.getMessage());
            }
        }
        else {
            response.sendError(500,"请求参数不合法");
        }
    }
}
